'''
Created on Jun 14, 2011

@author: oabalbin
'''
import sys
import os
import logging
import subprocess
from optparse import OptionParser
from config import ExomePipelineConfig, ExomeAnalysisConfig
from base import JOB_SUCCESS, JOB_ERROR
from exome.jobs.job_runner import qsub_cac, qsub_loc, run_local

# Global Variables
NODE_MEM=45000.0
NODE_CORES=12
SINGLE_CORE=1
MEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES)
# wt=walltime
WT_SHORT= "24:00:00"
WT_LONG= "60:00:00" #"100:00:00"
#user
USER='oabalbin'

def copy_dir(name, input_dir, output_dir, jobrunfunc, my_email, deps=None, remote=False, remote_ip=None):
    if remote:
        remote_ip="@".join([USER,remote_ip])        
        output_dir = ":".join([remote_ip, output_dir])
        args = ["scp", "-r", input_dir, output_dir] #"-P6248" use this whe you want to copy through path-dx8
        print args
    else:
        args = ["cp", "-r", input_dir, output_dir]
    
    '''
    jobidig = jobrunfunc('copying'+name, args, SINGLE_CORE, cwd=None, walltime=WT_LONG, pmem=MEM_PER_CORE, 
                          deps=deps, stdout=None, email_addresses=my_email)
    '''
    if subprocess.call(args) != 0:
        logging.error("Error copying dir file args='%s'" % str(args))
        return 1
    '''
    return jobidig
    '''
    return 0
    
def copy_dir_job(config_file, analysis_file, jobrunfunc,prev_deps):
    
    config = ExomePipelineConfig()
    config.from_xml(config_file)
    analysis = ExomeAnalysisConfig()
    # config.output dir is the folder results in cluster
    # analysis.output_dir is the one in the local machine to which you want to copy it.
    analysis.from_xml(analysis_file, config.output_dir)
    analysis.dst_output_dir
    my_email = config.email_addresses
    # check if output directory exist 
    
    '''
    if os.path.exists(analysis.dst_output_dir):
        logging.error("%s: Output directory %s does already exist" % (analysis.name, analysis.dst_output_dir))
        return JOB_ERROR
    '''
    # copy dir
    # copy sequence files to local output dir
    logging.info("%s: Copying results dir %s to %s remote=%s" % 
                 (analysis.name, config.output_dir, analysis.dst_output_dir, str(analysis.remote_ip)))
    if copy_dir(analysis.name, config.output_dir, analysis.dst_output_dir, \
                jobrunfunc, my_email, prev_deps, analysis.remote, analysis.remote_ip) != 0:
        logging.error("Error copying file %s" % config.output_dir)
        return JOB_ERROR
    return JOB_SUCCESS

if __name__ == '__main__': 
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    
    optionparser = OptionParser("usage: %prog [options] ")
    
    optionparser.add_option("-r", "--config_file", dest="config_file",
                            help="file with run configuration")
    optionparser.add_option("-a", "--analysis_file", dest="analysis_file",
                            help="file with experiment configuration") 
    optionparser.add_option("--local", dest="local", action="store_true", default=False)
    optionparser.add_option("--cluster", dest="cluster", action="store_true", default=False)
    optionparser.add_option("--local_cluster", dest="local_cluster", action="store_true", default=False)
    
    (options, args) = optionparser.parse_args()
    
    if not (options.local ^ options.cluster):
        optionparser.error("Must set either --local or --cluster to run job")
    if options.local:
        jobrunfunc = run_local
    elif options.cluster:
        jobrunfunc = qsub_cac
    elif options.local_cluster:
        jobrunfunc = qsub_loc

    prev_deps=[]
    sys.exit(copy_dir_job(options.config_file, options.analysis_file, jobrunfunc, prev_deps))